<template>
  <div class="yunbook-reader">
    <div id="read"></div>
  </div>
</template>

<script>
  import Epub from 'epubjs'
  import { bookMixin } from '../../utils/bookMixin'
  global.ePub = Epub
  export default {
    name: 'BookReader',
    mixins: [bookMixin],
    methods: {
      nextPage () {
        if (this.renditon) {
          this.renditon.next()
          this.hideTitleAndMenu()
        }
      },
      prevPage () {
        if (this.renditon) {
          this.renditon.prev()
          this.hideTitleAndMenu()
        }
      },
      toggleTitleAndMenu () {
        // this.$store.dispatch('setMenuVisible', !this.menuVisible)
        this.setMenuVisible(!this.menuVisible)
      },
      hideTitleAndMenu () {
        // this.$store.dispatch('setMenuVisible', false)
        this.setMenuVisible(false)
      },
      iniEpub () {
        const url = 'http://localhost:8081/epub/' + this.fileName + '.epub'
        this.book = new Epub(url)
        this.renditon = this.book.renderTo('read', {
          width: innerWidth,
          height: innerHeight,
          method: 'default'
        })
        this.renditon.display()
        this.renditon.on('touchstart', event => {
          this.touchStartX = event.changedTouches[0].clientX
          this.touchStartTime = event.timeStamp
        })
        this.renditon.on('touchend', event => {
          const offsetX = event.changedTouches[0].clientX - this.touchStartX
          const time = event.timeStamp - this.touchStartTime
          if (time < 500 && offsetX > 40) {
            this.prevPage()
          } else if (time < 500 && offsetX < -40) {
            this.nextPage()
          } else {
            this.toggleTitleAndMenu()
          }
        })
      }
    },
    mounted () {
      const fileName = this.$route.params.filename ? this.$route.params.filename : '1'
      this.$store.dispatch('setFileName', fileName).then(() => {
        this.iniEpub()
      })
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../assets/style/global";
</style>
